var config = {

    logoMargin: 10,
    logoBorderWidth: 3,
    logoBorderRadius: 10,
    logoVerticalOffset: 50,
    fontSize: '20px',
    indent: '50px',
    pixelsBetweenItems: '50px',
    earthColor: '#855723',
    greenColor: '#74C365',
    blueColor: '#87CEEB'
}

var info = {

}

function onResize(){

    info.documentWidth = $( document ).width();
    info.documentHeight = $( document ).height();
}

function onPageLoad() {
    
    info.documentWidth = $( document ).width();
    info.documentHeight = $( document ).height();

    initializeModalBox();

    makeLogoPretty();
    
    makeIntroTextPretty();

    makeCustomerInfoElements();

    $('#newPayment').attr( { 'disabled': '1' } );

    getCustomers();

}

function getCustomers() {

    $.ajax( { url: 'http://patchworkgardens.net/cgi-bin/getCustomers.py',
              type: 'GET',
              error: handleGetCustomerError,
              success: handleGetCustomerResponse } );

    $('#modalBoxTitle').text( '' );
   
    $('#modalBoxForm').append(
        makeEl('div').attr( { 'class': 'modalText' } ).text( 'Retrieving Customers...' ) );
    
    $('#modalBoxContainer').show( 'slow', alignModalBox );
}

function handleGetCustomerError() {

    $('#modalBoxTitle').text( 'Ehhhh' );
   
    $('#modalBoxForm').append(
        makeEl('div').attr( { 'class': 'modalText' } ).text( 'There was an error retrieving the customer data.  Refresh the page my son.' ) );
    
    $('#modalBoxContainer').show( 'slow', alignModalBox );
}

function handleGetCustomerResponse( response ) {

    info.customers = eval( '(' + response + ')' );

    closeModalBox();
}


function showModalText( text ) {
 
    $('#modalBoxTitle').text( 'Not so fast' );
   
    $('#modalBoxForm').append(
        makeEl('div').attr( { 'class': 'modalText' } ).text( text ) );
    
    $('#modalBoxContainer').show( 'slow', alignModalBox );
}

function handleSubmitClick() {

    $('.submitButton').unbind('click');
    
    if( ! info.currentCustomerId ) { showModalText( 'Unable to find a customerId - select a name again.' ); $('.submitButton').bind('click',{}, handleSubmitClick); return; }
    
    if( ! $('#amountPaid').text() ) { showModalText( 'Unable to find amount paid - select a name again.' ); $('.submitButton').bind('click',{}, handleSubmitClick); return; }
    
    if( ! $('#amountOwed').text() ) { showModalText( 'Unable to find amount owed - select a name again.' ); $('.submitButton').bind('click',{}, handleSubmitClick); return; }
    
    if( ! $('#emailAddress').text() ) { showModalText( 'Unable to find emailAddress - select a name again.' ); $('.submitButton').bind('click',{}, handleSubmitClick); return; }
    
    if( parseFloat( $('#newPayment').val() ) == 0 ) { showModalText( 'Received Payment is $0.00.  Try again my son.' ); $('.submitButton').bind('click',{}, handleSubmitClick); return; }

    var url = [ 'http://patchworkgardens.net/cgi-bin/weGotCash.py?customerId=',
                        encodeURIComponent( info.currentCustomerId ),
                        '&amountPaid=',
                        encodeURIComponent( $('#amountPaid').text() ),
                        '&amountOwed=',
                        encodeURIComponent( $('#amountOwed').text() ),
                        '&emailAddress=',
                        encodeURIComponent( $('#emailAddress').text() ),
                        '&newPayment=',
                        encodeURIComponent( $('#newPayment').val() ) 
                ].join('');

    $.ajax( { url: url,
              type: 'GET',
              error: handleErrorResponse,
              success: handleSubmitResponse } );

    showModalWait();   
}

function showModalWait() {

    $('#modalBoxTitle').text( '' );
    $('#modalBoxForm').append( makeEl('div').attr( { 'class': 'modalText' } ).text( 'Please Wait.' ) );

    info.modalWait = true;
    
    $('#modalBoxContainer').show( 'slow', alignModalBox );
}

function handleErrorResponse() {

    $( $('#modalBoxForm div.modalText')[0] ).text( "There was an error.  Try again.  If it happens three times in a row, its probably a bug." );
    info.modalWait = false;
    alignModalBox();
    $('.submitButton').bind('click',{}, handleSubmitClick);
}

function handleSubmitResponse( response ) {

    var responseObj = eval( '(' + response + ')' );

    if( responseObj.error ) {

        $( $('#modalBoxForm div.modalText')[0] ).text( 'There was an error.  Try again.  If it happens three times in a row, its probably a bug.' );
        info.modalWait = false;
        alignModalBox();
        $('.submitButton').bind('click',{}, handleSubmitClick);

    } else if( $.trim( responseObj.emailError ) == 'True' ) {

        $( $('#modalBoxForm div.modalText')[0] ).text( 'There was an error sending the email out.  The database has been updated.' );
        info.modalWait = false;
        alignModalBox();
        $('.submitButton').bind('click',{}, handleSubmitClick);


    } else {
        
        $( $('#modalBoxForm div.modalText')[0] ).text( 'Great Success!' );
        alignModalBox();
        setTimeout( function() { closeModalBox(); location.reload(); }, 5000 );
    }
}

function handleNameKeyDown() {

    info.currentCustomerId = undefined;
    $('#emailAddress').text( '' );
    $('#amountOwed').text( '' );
    $('#amountPaid').text( '' );
    $('#newPayment').attr( { 'disabled': '1' } );

    var nameVal = $('#nameField').val();

    if( info.matchedNameDiv ) {

        info.matchedNameDiv.empty().remove();
    }

    info.matchedNameDiv = makeEl('div');

    $('#customerInfo').append(
            info.matchedNameDiv.css( { 'position': 'absolute',
                                       'background-color': 'white',
                                       'border': '1px solid blue',
                                       'z-index': 1000,
                                       'max-height': '200px',
                                       'overflow': 'scroll',
                                       'top': $('#nameField').offset().top + $('#nameField').outerHeight( true ),
                                       'left': $('#nameField').offset().left } ) );

    for( var i = 0, ii = info.customers.length; i < ii; i++ ) {
   
        var re = new RegExp( nameVal, "i" );

        if( re.test( info.customers[i].name ) ) {

            info.matchedNameDiv.append(
                makeEl('div').text( info.customers[i].name )
                             .css( { 'z-index': 1000 } )
                             .hover( setMouseToPointer, setMouseToDefault )
                             .hover( function() { $(this).css({'background-color': 'yellow' } ); }, function() { $(this).css({'background-color': 'white'}); } )
                             .bind( 'click', { info: info.customers[i] }, handleMatchedNameClick ) );
        }
    }

    if( info.matchedNameDiv.children().length == 0 ) {

        info.matchedNameDiv.append( makeEl('div').text('No Matches') );
    }

    $(document).bind( 'click', { }, closeCustomerDropDown );
}

function closeCustomerDropDown() {

    if( info.matchedNameDiv ) {
        info.matchedNameDiv.hide();
    }
}

function handleMatchedNameClick( e ) {

    info.currentCustomerId = e.data.info.id

    $('#nameField').val( e.data.info.name );
    $('#emailAddress').text( e.data.info.emailAddress );
    $('#amountOwed').text( e.data.info.amountOwed );
    $('#amountPaid').text( e.data.info.amountPaid );
    $('#newPayment').removeAttr('disabled').val( '0.00' );

}

function makeCustomerInfoElements() {

    $('#customerInfo').css( { 'margin-top': config.pixelsBetweenItems,
                              'min-width': '1036px',
                              'overflow': 'hidden',
                              'margin-left': config.indent,
                              'font-size': config.fontSize } ).append(
       makeEl('div').css( { 'margin': '0px 0px 50px 0px' } ).append(
           makeEl('div').css( { 'float': 'left', 'margin-right': '50px' } ).append(
               makeEl('div').css( { 'float': 'left',
                                    'padding': '5px',
                                    'font-weight': 'bold' } ).text( 'Name : ' ),
               makeEl('input').attr( { 'id': 'nameField',
                                       'autocomplete': 'off',
                                       'type': 'text',
                                       'size': '43',
                                       'name': 'name' } )
                              .bind( 'keyup', { }, handleNameKeyDown )
                              .css( { 'padding': '5px' } ) ),
           makeEl('div').css( { 'clear': 'both' } ) ),
           makeEl('div').css( { 'float': 'left' } ).append(
               makeEl('div').css( { 'float': 'left',
                                    'padding': '5px',
                                    'font-weight': 'bold' } ).text( 'Amount Paid : ' ),
               makeEl('span').attr( { 'id': 'amountPaid' } )
                              .css( { 'line-height': '35px', 'padding': '5px' } ) ),
           makeEl('div').css( { 'float': 'left', 'margin-right': '50px' } ).append(
               makeEl('div').css( { 'float': 'left',
                                    'margin-left': '50px',
                                    'padding': '5px',
                                    'font-weight': 'bold' } ).text( 'Amount Owed : ' ),
               makeEl('span').attr( { 'id': 'amountOwed' } )
                              .css( { 'line-height': '35px', 'padding': '5px' } ) ),
       makeEl('div').css( { 'margin': '0px 0' } ).append(
           makeEl('div').css( { 'float': 'left' } ).append(
                          makeEl('div').css( { 'float': 'left',
                                               'padding': '5px',
                                               'font-weight': 'bold' } ).text( 'Email Address : ' ),
                          makeEl('span').attr( { 'id': 'emailAddress' } )
                              .css( { 'line-height': '35px', 'padding': '5px' } ) ),
           makeEl('div').css( { 'clear': 'both' } ) ),
       makeEl('div').css( { 'margin': '0px 0' } ).append(
           makeEl('div').css( { 'float': 'left' } ).append(
                          makeEl('div').css( { 'float': 'left',
                                               'padding': '5px',
                                               'font-weight': 'bold' } ).text( "We've received payment in the amount of : " ),
                          makeEl('input').attr( { 'id': 'newPayment',
                                                  'type': 'text',
                                                  'size': '10',
                                                  'value': '0.00' } )
                                         .css( { 'padding': '5px' } ) ),
           makeEl('div').attr( { 'class': 'submitButton' } ).text('Add the gold.'),
           makeEl('div').css( { 'clear': 'both' } ) ) );


    $('.submitButton').css( { 'margin-left': ( ( info.documentWidth - ( parseInt( config.indent ) * 2 ) - $('.submitButton').outerWidth( true ) ) / 2 ) } )
                      .bind( 'click', {}, handleSubmitClick );
}

function makeLogoPretty() {

    $('#logoImage')
        .css( { 'float': 'left',
                'background-image': 'url(Images/jsLogo.png)',
                'height': '209px',
                'width': '540px',
                'margin': [ config.logoMargin, 'px' ].join('') } );
    
    $('#logoBorder3').css( { 'float': 'left',
                             'margin': [ config.logoMargin, 'px' ].join(''),
                             '-moz-border-radius': [ config.logoBorderRadius, 'px' ].join(''),
                             'border-radius': [ config.logoBorderRadius, 'px' ].join(''),
                             'border': [ config.logoBorderWidth, 'px solid ', config.earthColor ].join('') } );
    
    $('#logoBorder2').css( { 'float': 'left',
                             'margin': [ config.logoMargin, 'px' ].join(''),
                             '-moz-border-radius': [ config.logoBorderRadius, 'px' ].join(''),
                             'border-radius': [ config.logoBorderRadius, 'px' ].join(''),
                             'border': [ config.logoBorderWidth, 'px solid ', config.greenColor ].join('') } );
    
    $('#logoBorder1').css( { 'float': 'left',
                             '-moz-border-radius': [ config.logoBorderRadius, 'px' ].join(''),
                             'border-radius': [ config.logoBorderRadius, 'px' ].join(''),
                             'border': [ config.logoBorderWidth, 'px solid ', config.blueColor ].join('') } );

    $('#logoContainer')
        .height( $('#logoBorder1').outerHeight( true ) )
        .width( $('#logoBorder1').outerWidth( true ) )
        .css( { 'float': 'left',
                'margin-top': '20px',
                'margin-left': ( ( info.documentWidth - $('#logoBorder1').outerWidth( true ) ) / 2 ) } )
        .after( makeEl('div').css( { 'clear': 'both' } ) );
}

function initializeModalBox() {

    $('body').append(
        makeEl('div').attr( { 'id': 'modalBoxContainer' } ).append(
            makeEl('div').attr( { 'class': 'modalBoxOverlay' } ),
            makeEl('div').attr( { 'id': 'modalBoxContent' } ).append(
                makeEl('div').attr( { 'id': 'modalBoxTitle' } ),
                makeEl('div').attr( { 'id': 'modalBoxForm' } ) ) ) );
}

function makeIntroTextPretty() {

    $( '#introductionText' ).css( { 'margin-top': '30px',
                                    'min-width': '1036px',
                                    'overflow': 'hidden' } );
    
    $( '.introductionText' ).css( { 'text-align': 'center', 'font-size': '20px' } );
}
   
function alignModalBox() {

    var content = $('#modalBoxContent');
    var form = $('#modalBoxForm');

    content.css( { top: ( ( info.documentHeight - content.outerHeight( true ) ) / 2 ),
                   left: ( ( info.documentWidth - content.outerWidth( true ) ) / 2 ) } );
         
    if( ! info.modalWait ) {

        $( document ).bind( 'keydown', handleModalKeyPress );
        $( document ).bind( 'click', handleModalMouseClick );
    }
}

function handleModalKeyPress( e ) { if( e.keyCode == 27 ) { closeModalBox(); } }

function handleModalMouseClick( e ) {

    if( ! ( isMouseOnElement( { x: e.pageX, y: e.pageY, el: $( '#modalBoxContent' ) } ) ) ) { closeModalBox(); }
}

function isMouseOnElement( p ) {

    var elementOffset = p.el.offset();

    if( p.x < elementOffset.left || p.y < elementOffset.top ||
        p.x > ( elementOffset.left + p.el.outerWidth( true ) ) ||
        p.y > ( elementOffset.top + p.el.outerHeight( true ) ) ) {

        return false;

    } else { return true; }
}

function closeModalBox() {

    $('#modalBoxTitle').text('');

    $('#modalBoxForm').empty();

    $('#modalBoxContainer').hide();
    
    if( !info.modalWait ) {
        $(document).unbind( 'keydown', handleModalKeyPress );
        $(document).unbind( 'click', handleModalMouseClick );
    } else {
        info.modalWait = false;
    }
}

function makeEl( elementName ) { return $(document.createElement(elementName)); }
function setMouseToPointer() { document.body.style.cursor = 'pointer'; }
function setMouseToDefault() { document.body.style.cursor = 'default'; }


$( window ).load( onPageLoad );
$( window ).resize( onResize );
